//dataStr日期字符串
//dayCount 要增加的天数
function dateAddDays(dataStr,dayCount) {
    var strdate=dataStr; //日期字符串
    var isdate = new Date(strdate.replace(/-/g,"/"));  //把日期字符串转换成日期格式
    isdate = new Date((isdate/1000+(86400*dayCount))*1000);  //日期加1天
    var pdate = isdate.getFullYear()+"-"+(isdate.getMonth()+1)+"-"+(isdate.getDate());   //把日期格式转换成字符串

    return pdate;
}
//计算日期相差天数
function  DateDiff(sDate1,  sDate2){    //sDate1和sDate2是2006-12-18格式  
    var  aDate,  oDate1,  oDate2,  iDays  
    aDate  =  sDate1.split("-")  
    oDate1  =  new  Date(aDate[1]  +  '-'  +  aDate[2]  +  '-'  +  aDate[0])    //转换为12-18-2006格式  
    aDate  =  sDate2.split("-")  
    oDate2  =  new  Date(aDate[1]  +  '-'  +  aDate[2]  +  '-'  +  aDate[0])  
    iDays  =  parseInt(Math.abs(oDate1  -  oDate2)  /  1000  /  60  /  60  /24)    //把相差的毫秒数转换为天数  
    return  iDays  
} 

$(document).ready(function(){
	var rootPath = getRootPath();
	
	$.ajax({
		method : 'get',
		url : rootPath+'/wechat/api/potentialUsers/personalPhoto',
		error:function(XMLHttpRequest, ajaxOptions, thrownError){
			alert("数据刷新失败");
		},
		success : function(resultData){

			$.each(resultData,function(personalPhotoIndex,personalPhotoObj){
				headImgurl = personalPhotoObj.headImgurl;

				$("#Imgurl").attr('src',headImgurl);
				$("#headImgurl").val(headImgurl); 
				});
		}
	});
	
	$.ajax({
		method : 'get',
		url : rootPath+'/wechat/api/potentialUsers',
		error:function(XMLHttpRequest, ajaxOptions, thrownError){
			alert("连接服务器错误!");
		},
		success : function(resultData){
			
			$.each(resultData,function(personalIndex,personalObj){

				userId = personalObj.userId;
				dealerCode = personalObj.dealerCode;
				
				$("#userId").val(userId);
				$("#potentialUserId").val(personalObj.potentialUserId);
				$("#dealerCode").val(dealerCode);
				
				$('#jiu').attr('href','homepage/soshelp.html?carOwnerUserId='+$('#carUserId').val()); 
				$('#yang').attr('href','homepage/maintain.html?userId='+$('#carUserId').val()); 
				$('#shi').attr('href','homepage/testdriving.html?userId='+$('#carUserId').val()+'&dealerCode='+dealerCode+'&potentialUserId='+$("#potentialUserId").val()); 
			});
		}
	});
	
	$.ajax({
        type:"GET", 
        url:rootPath+"/wechat/api/maintain/getBindCarInfos", 
        dataType:"json",      
        async: false,
        contentType:"application/json",               
        data:null, 
        success:function(data){ 
        	if (data.length==0){
        		alert("您还没有绑定车辆，请先绑定车辆。");
        		//to_bingCar();// 编辑轮播信息数据
    			var wholeHtml = '';
    			// 轮播（Carousel）指标
    			var carousel_indicatorsHtml = '<ol class="carousel-indicators">';
    			
    			// 轮播（Carousel）项目
    			var carousel_innerHtml = '';
    			
    			var indexTemp= 0;
    			
    			carousel_innerHtml += "<div class='item'>";
    			carousel_innerHtml += "<table><tr><td><a href='#' onclick='to_bingCar()' >";
    			carousel_innerHtml += '<img src="'+rootPath+'/images/allCar.png'+'" width="110" height="60">';
    			carousel_innerHtml +="</a></td><td nowrap='nowrap' align='center' valign='middle'><div class=''>";
    			carousel_innerHtml += "<p>";
    			carousel_innerHtml +="<h5  style='font: bolder;color: #000'><a href='#' onclick='to_bingCar()' >　绑定车辆？</a></h5>";
    			carousel_innerHtml +="</div></td></tr></table>";
    			carousel_innerHtml +="<input type='hidden' id = 'vin_"+indexTemp+1+"' value='' /></div>";
    			
    			
    			carousel_indicatorsHtml += "</ol> ";
    			carousel_innerHtml += "</div>";
    			
    			// 轮播（Carousel）导航
//    			var carousel_controlHtml = '<a class="carousel-control left"  href="#myCarInfos"  data-slide="prev" type = "button">&lsaquo;</a>';
//    			    carousel_controlHtml += '<a class="carousel-control right" href="#myCarInfos"  data-slide="next" type = "button">&rsaquo;</a>';
//    			
    			$("#myCarInfos").append(carousel_indicatorsHtml);
    			$("#myCarInfos").append(carousel_innerHtml);

        	}else{
            // 编辑轮播信息数据
			var wholeHtml = '';
			// 轮播（Carousel）指标
			var carousel_indicatorsHtml = '<ol class="carousel-indicators" style="width:70%">';
			
			// 轮播（Carousel）项目
			var carousel_innerHtml = '<div class="carousel-inner">';
			
			var indexTemp= 0;
			$.each(data,function(carModelIndex,carModelObj){
				indexTemp = carModelIndex;
				if (0 == carModelIndex){
					
//				    carousel_indicatorsHtml+= '<li data-target="#myCarInfos" data-slide-to='+carModelIndex+' class="active"></li>';
					carousel_indicatorsHtml += '<li class="active"><a href="#" class="active" onclick=setVin('+carModelIndex+')><img alt="" src="'+rootPath+'/images/'+carModelObj.brandName+'/外观/'+carModelObj.seriesName+'/'+carModelObj.seriesName+'.jpg'+'"  data-target="#myCarInfos" data-slide-to="'+ carModelIndex +'" class="img-responsive"/ ></a></li>';
				    carousel_innerHtml += "<div class='item active'>";
				    //品牌CODE赋值
				    $("#vin").val(carModelObj.vin);
				    $("#carId").val(carModelObj.carId);
				    $("#carUserId").val(carModelObj.userId);
				} else {
//					carousel_indicatorsHtml+= '<li data-target="#myCarInfos" data-slide-to='+carModelIndex+' ></li>';
					carousel_indicatorsHtml += '<li><a href="#" onclick=setVin('+carModelIndex+')><img alt="" src="'+rootPath+'/images/'+carModelObj.brandName+'/外观/'+carModelObj.seriesName+'/'+carModelObj.seriesName+'.jpg'+'"  data-target="#myCarInfos" data-slide-to="'+carModelIndex+'" class="img-responsive"/ ></a></li>';
					carousel_innerHtml += "<div class='item'>";
				}
				
				carousel_innerHtml += '<table><tr>';
				carousel_innerHtml +="</td><td nowrap='nowrap' align='center' valign='middle'><div class=''>";
				carousel_innerHtml += "<p>";
				carousel_innerHtml +="<h4  style='font: bolder;color: #000'>"+carModelObj.registNo+"</h4>";
				carousel_innerHtml +="<span class='text-muted'>"+carModelObj.seriesName+"</span>";
				carousel_innerHtml +='<td width="70%"><a href="'+rootPath+'/views/homepage/editCarinfo.html?carId='+carModelObj.carId+'"><img src="'+rootPath+'/images/'+carModelObj.brandName+'/外观/'+carModelObj.seriesName+'/'+carModelObj.seriesName+'.jpg'+'" width="120" height="60"></a>';
				carousel_innerHtml +="</div></td></tr></table>";
				carousel_innerHtml +="<input type='hidden' id = 'vin_"+carModelIndex+"' value='"+carModelObj.vin+"' />";
				carousel_innerHtml +="<input type='hidden' id = 'carUserId_"+carModelIndex+"' value='"+carModelObj.userId+"' />";
				carousel_innerHtml +="<input type='hidden' id = 'carId_"+carModelIndex+"' value='"+carModelObj.carId+"' /></div>";
			});
			
			carousel_innerHtml += "<div class='item'>";
			carousel_innerHtml += "<table><tr><td><a href='#' onclick='to_bingCar()' >";
			carousel_innerHtml += '<img src="'+rootPath+'/images/allCar.png'+'" width="110" height="60">';
			carousel_innerHtml +="</a></td><td nowrap='nowrap' align='center' valign='middle'><div class=''>";
			carousel_innerHtml += "<p>";
			carousel_innerHtml +="<h5  style='font: bolder;color: #000'><a href='#' onclick='to_bingCar()' >　绑定车辆？</a></h5>";
			carousel_innerHtml +="</div></td></tr></table>";
			carousel_innerHtml +="<input type='hidden' id = 'vin_"+indexTemp+1+"' value='' /></div>";
			
			
			carousel_indicatorsHtml += "</ol> ";
			carousel_innerHtml += "</div>";
			
			// 轮播（Carousel）导航
//			var carousel_controlHtml = '<a class="carousel-control left"  href="#myCarInfos"  data-slide="prev" type = "button">&lsaquo;</a>';
//			    carousel_controlHtml += '<a class="carousel-control right" href="#myCarInfos"  data-slide="next" type = "button">&rsaquo;</a>';
//			
			$("#myCarInfos").append(carousel_indicatorsHtml);
			$("#myCarInfos").append(carousel_innerHtml);
			
			// 停止自动轮播
			$('#myCarInfos').carousel({
				interval: false
			})
			// 停止自动轮播
			$("#myCarInfos").carousel('pause');
			
/////////////////////////////////////
			
			$('#myCarInfos').hammer().on('swipeleft', function(){
				$(this).carousel('next');
			});
			
			$('#myCarInfos').hammer().on('swiperight', function(){
				$(this).carousel('prev');
			});

////////////////////////////////////
        	var vin = $("#vin").val();
        	var d = new Date();
        	var date = d.getFullYear()+"-"+(d.getMonth()+1)+"-"+d.getDate();
        	$.ajax({
        		method : 'get',
        		url : rootPath+'/wechat/api/potentialUsers/personalInsure/'+vin,
        		error:function(XMLHttpRequest, ajaxOptions, thrownError){
        			//alert("还没有绑定车辆!");
        		},
        		success : function(resultData){

        			$.each(resultData,function(personalInsureIndex,personalInsureObj){
        				
        				var lastInsuerDate = personalInsureObj.lastInsureDate;
        				var nextInsuerDate = dateAddDays(lastInsuerDate,364);
        				var da = DateDiff(nextInsuerDate,date);
        				$("#nextInsureDate").html(da+'天');
        				});
        		}
        	});
        	
        	$.ajax({
        		method : 'get',
        		url : rootPath+'/wechat/api/potentialUsers/personalMaintain/'+vin,
        		error:function(XMLHttpRequest, ajaxOptions, thrownError){
        			//alert("还没有绑定车辆!");
        		},
        		success : function(resultData){

        			$.each(resultData,function(personalMaintainIndex,personalMaintainObj){
        				var lastMaintainDate = personalMaintainObj.lastMaintainDate;
        				var nextMaintainDate = dateAddDays(lastMaintainDate,(personalMaintainObj.vals)*30);
        				var da = DateDiff(nextMaintainDate,date);
        				$("#nextMaintainDate").html(da+'天');
        				$("#date").val(da);
        				});
        		}
        	});
           }
        },
        error:function(data){
        	alert("数据刷新失败，请联系管理员！");
        }
     });
     
     
	/**
	 * 设置选择的车型
	 * @param index
	 * @returns
	 */
	function setVin(index){
		$("#vin").val($("#vin_"+index).val());
		$("#carId").val($("#carId_"+index).val());
		$("#carUserId").val($("#carUserId_"+index).val());
	}
	
	/**
	 * 监听轮播信息
	 */
	$(function(){
	    $('#myCarInfos').on('slid.bs.carousel', function (e) {
	    	 var active = $(e.target).find('.carousel-inner > .item.active');
	    	 var ccindex = active.index();
	    	  $("#vin").val($("#vin_"+ccindex).val());
	    	  $("#carId").val($("#carId_"+ccindex).val());
	    	  $("#carUserId").val($("#carUserId_"+ccindex).val());
	    });
	});
	
	
	/**
	 * 设置选择的车型
	 * @param index
	 * @returns
	 */
	function setVin(index){
		$("#vin").val($("#vin_"+index).val());
		$("#carId").val($("#carId_"+index).val());
		$("#carUserId").val($("#carUserId_"+index).val());
	}
	
	/**
	 * 监听轮播信息
	 */
	$(function(){
	    $('#myCarInfos').on('slid.bs.carousel', function (e) {
	    	 var active = $(e.target).find('.carousel-inner > .item.active');
	    	 var ccindex = active.index();
	    	  $("#vin").val($("#vin_"+ccindex).val());
	    	  $("#carId").val($("#carId_"+ccindex).val());
	    	  $("#carUserId").val($("#carUserId_"+ccindex).val());
	    });
	});
	$("#deleteCar").click(function(){
		$('#myModal').modal({
				keyboard: false,
				backdrop:false
			});
		$('#modalSure').click(function(){
			var data={
			userId:"",
			carId:"",
	    }; 
	    data.userId = $.trim($("#carUserId").val()); 
	    data.carId = $.trim($("#carId").val());
	   
		$.ajax({
			type : 'POST',
			url : rootPath+'/wechat/api/vehicleBinding/updateOwnerCar',
			contentType:"application/json",
			data: JSON.stringify(data),
			error:function(XMLHttpRequest, ajaxOptions, thrownError){
				alert("删除车辆失败");
			},
			success : function(data){
				$('#deleteCarModal').modal({
					keyboard: false,
					backdrop:false
				});
			}
		});
	  });
	});
})
/**
 * 跳转到绑定车辆页面
 * 
 * @returns
 */
function to_bingCar(){
	
	window.location = rootPath + "/views/vehicleBinding/vehicleBinding.html";
}
/**
 * 跳转到个人中心页面
 * 
 * @returns
 */
function re(){
	window.location = rootPath + "/views/hp.html";
}